package cn.throwx.sc.ch2;

import org.springframework.security.crypto.argon2.Argon2PasswordEncoder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.DelegatingPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.crypto.password.Pbkdf2PasswordEncoder;
import org.springframework.security.crypto.password.StandardPasswordEncoder;
import org.springframework.security.crypto.scrypt.SCryptPasswordEncoder;

import java.util.HashMap;
import java.util.Map;

/**
 * @author throwable
 * @version v1
 * @description DelegatingPasswordEncoder demo
 * @since 2021/10/31 1:05
 */
public class DelegatingPasswordEncoderDemo {

    private static final String RAW_PD = "throwable";

    public static void main(String[] args) {
        Map<String, PasswordEncoder> idToPasswordEncoder = new HashMap<>();
        idToPasswordEncoder.put("argon2", new Argon2PasswordEncoder());
        idToPasswordEncoder.put("bcrypt", new BCryptPasswordEncoder());
        idToPasswordEncoder.put("pbkdf2", new Pbkdf2PasswordEncoder());
        idToPasswordEncoder.put("scrypt", new SCryptPasswordEncoder());
        idToPasswordEncoder.put("sha256", new StandardPasswordEncoder());
        // 假设项目刚开始的时候,使用sha256进行encode,其他都是用于match
        DelegatingPasswordEncoder delegatingPasswordEncoderBefore
                = new DelegatingPasswordEncoder("sha256", idToPasswordEncoder);
        String beforeEncodedPd = delegatingPasswordEncoderBefore.encode(RAW_PD);
        // 后来项目修改密码的编码方式,使用bcrypt进行encode,其他都是用于match
        DelegatingPasswordEncoder delegatingPasswordEncoderAfter
                = new DelegatingPasswordEncoder("bcrypt", idToPasswordEncoder);
        String afterEncodedPd = delegatingPasswordEncoderAfter.encode(RAW_PD);
        System.out.println("afterEncodedPd=>delegatingPasswordEncoderBefore,match:"
                + delegatingPasswordEncoderBefore.matches(RAW_PD, afterEncodedPd));
        System.out.println("beforeEncodedPd=>delegatingPasswordEncoderAfter,match:"
                + delegatingPasswordEncoderAfter.matches(RAW_PD, beforeEncodedPd));
    }
}
